﻿using System.Windows.Forms;
using Microsoft.Win32;

namespace System
{
    public class AssociateEqsFile
    {
        public bool CheckFileAssociation(string typeName)
        {
            try
            {
                RegistryKey isExCommand = Registry.ClassesRoot.OpenSubKey(typeName);
                if (isExCommand == null)
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        public bool CreateFileAssociation(string extension, string typeName, string descrition)
        {
            if (!CheckFileAssociation(typeName))
            {
                try
                {
                    RegistryKey typeNameKey = Registry.ClassesRoot.CreateSubKey(typeName);
                    typeNameKey.SetValue("Create", Application.ExecutablePath);
                    typeNameKey.SetValue("", descrition);

                    RegistryKey typeIconKey = typeNameKey.CreateSubKey("DefaultIcon");
                    typeIconKey.SetValue("", Application.ExecutablePath + ",0");

                    RegistryKey shellKey = typeNameKey.CreateSubKey("Shell");
                    RegistryKey shellOpenKey = shellKey.CreateSubKey("Open");
                    RegistryKey shellOpenCommandKey = shellOpenKey.CreateSubKey("Command");

                    shellOpenCommandKey.SetValue("", string.Format("\"{0}\" \"%1\"", Application.ExecutablePath));

                    RegistryKey extesionKey = Registry.ClassesRoot.CreateSubKey(extension);
                    extesionKey.SetValue("", typeName);

                    extesionKey.Close();
                    shellOpenCommandKey.Close();
                    shellOpenKey.Close();
                    shellKey.Close();
                    typeIconKey.Close();
                    typeNameKey.Close();
                }
                catch (Exception)
                {
                    return false;
                }
            }

            return true;
        }
    }
}
